package com.egd.imapp.contoller.activity.chat;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.egd.imapp.R;
import com.egd.imapp.contoller.activity.contact.PickContactActivity;
import com.egd.imapp.contoller.adapter.GroupDetailAdapter;
import com.egd.imapp.model.Model;
import com.egd.imapp.model.bean.UserInfo;
import com.egd.imapp.utils.Constant;
import com.egd.imapp.utils.CustomDialog;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

public class GroupDetailActivity extends AppCompatActivity {
    private static final String TAG = "TAG";
    private RelativeLayout rl_group_detail_title;
    private ImageView mBack;
    private TextView tv_group_host_name;
    private TextView mCancel;
    private TextView tv_group_detail_counts;
    private GridView gv_member_list;
    private Button btn_exit_or_release_group;
    private EMGroup emGroup;
    private GroupDetailAdapter.OnGroupDetailListener mOnGroupDetailListener = new GroupDetailAdapter.OnGroupDetailListener() {
        @Override
        public void onAddMembers() {
            Toast.makeText(GroupDetailActivity.this, "添加群成员", Toast.LENGTH_SHORT).show();
            // 携带数据跳转到选择联系人页面
            Intent intent = new Intent(GroupDetailActivity.this, PickContactActivity.class);
            // 传递群id
            intent.putExtra(Constant.GROUP_ID, emGroup.getGroupId());

            startActivityForResult(intent, 2);
        }

        @Override
        public void onDeleteMember(UserInfo user) {
            Toast.makeText(GroupDetailActivity.this, "删除群成员 user = " + user, Toast.LENGTH_SHORT).show();
            showDeleteMemberDialog(user);
        }

        @Override
        public void onShowCancelDelete() {
            Toast.makeText(GroupDetailActivity.this, "删除群成员", Toast.LENGTH_SHORT).show();
            // 显示取消按钮
            mCancel.setVisibility(View.VISIBLE);

        }
    };
    private ArrayList<UserInfo> mUsers;
    private GroupDetailAdapter groupDetailAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);

        initView();
        
        initIntent();
        
        initData();

        initListener();
    }

    private void initListener() {
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        // 取消删除模式
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                groupDetailAdapter.setCancelDelete();
                mCancel.setVisibility(View.GONE);
            }
        });
    }

    private void initData() {
        // 初始化button显示
        initButtonDisplay();

        // 初始化gridview
        initGridView();
        
        // 从环信服务器获取所有的群成员
        getMembersFromHxServer();

        // 初始化群主和群人数
        tv_group_host_name.setText(emGroup.getOwner());

        if (emGroup.getGroupPermissionType().equals("owner")){
            tv_group_detail_counts.setText("群成员: "+ emGroup.getMemberCount());
        }else {
            tv_group_detail_counts.setText("群成员: "+ (emGroup.getMemberCount() - 1));
        }
    }

    private void getMembersFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 从环信服务器中获取所有的群成员信息
//                    EMGroup group = EMClient.getInstance().groupManager().getGroupFromServer(emGroup.getGroupId(), true);

                    //如果群成员较多，需要多次从服务器获取完成

                    List<String> members = new ArrayList<>();
                    EMCursorResult<String> result = null;
                    final int pageSize = 20;
                    do {
                        result = EMClient.getInstance().groupManager().fetchGroupMembers(emGroup.getGroupId(),
                                result != null ? result.getCursor() : "", pageSize);
                        members.addAll(result.getData());
                    } while (!TextUtils.isEmpty(result.getCursor()) && result.getData().size() == pageSize);

                    Log.e(TAG, "initIntent: membsers = " + members + " 人数 = " + members.size() );

                    if (members != null && members.size() >=0){
                        mUsers = new ArrayList<>();

                        // 转化
                        for (String member : members){
                            UserInfo userInfo = new UserInfo(member);

                            mUsers.add(userInfo);
                        }
                    }

                    tv_group_detail_counts.setText("群成员: "+ members.size());

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            // 刷新适配器
                            groupDetailAdapter.refresh(mUsers);
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this, "获取群信息失败 原因：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void initGridView() {
        // 当前用户是群主或者当前群是公开的
        boolean isCanModify = EMClient.getInstance().getCurrentUser().endsWith(emGroup.getOwner()) || emGroup.isPublic() ;
        // 允许群成员邀请其他人入群
        boolean isMemberAllowToInvite = emGroup.isMemberAllowToInvite();

        groupDetailAdapter = new GroupDetailAdapter(this, isCanModify, mOnGroupDetailListener);

        groupDetailAdapter.setMemberAllowToInvite(isMemberAllowToInvite);

        gv_member_list.setAdapter(groupDetailAdapter);
    }

    private void initButtonDisplay() {
        // 群主 具有解散群的权限
        if (EMClient.getInstance().getCurrentUser().equals(emGroup.getOwner())){

            btn_exit_or_release_group.setText("解散群");

            btn_exit_or_release_group.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    showReleaseGroupDialog(emGroup.getGroupName());

                }
            });
        }else {
            // 普通群成员
            btn_exit_or_release_group.setText("退 群");
            btn_exit_or_release_group.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showSignOutGroupDialog(emGroup.getGroupName());

                }
            });

        }
    }


    private void exitGroupBroadCast() {
        LocalBroadcastManager mLBM = LocalBroadcastManager.getInstance(GroupDetailActivity.this);

        Intent intent = new Intent(Constant.EXIT_GROUP);

        intent.putExtra(Constant.GROUP_ID, emGroup.getGroupId());

        mLBM.sendBroadcast(intent);
    }

    private void initIntent() {
        // 通过群id获取群信息
        Intent intent = getIntent();
        String groupId = intent.getStringExtra(Constant.GROUP_ID);
        if (groupId == null){
            return;
        }else {
            emGroup = EMClient.getInstance().groupManager().getGroup(groupId);
            //hhahaha = 165518608760833
            Log.e(TAG, "initIntent: groupId = " + groupId );
            Log.e(TAG, "initIntent: getGroupName = " + emGroup.getGroupName() );
            Log.e(TAG, "initIntent: getMemberCount = " + emGroup.getMemberCount() );
            Log.e(TAG, "initIntent: getOwner = " + emGroup.getOwner() );
            Log.e(TAG, "initIntent: getGroupId = " + emGroup.getGroupId() );
            Log.e(TAG, "initIntent: getGroupPermissionType = " + emGroup.getGroupPermissionType() );
            final List<String> members = emGroup.getMembers();
            Log.e(TAG, "initIntent: membsers = " + members + " 人数 = " + members.size() );
        }
    }

    private void initView() {
        rl_group_detail_title = findViewById(R.id.rl_group_detail_title);
        tv_group_host_name = findViewById(R.id.tv_group_host_name);
        tv_group_detail_counts = findViewById(R.id.tv_group_detail_counts);
        mBack = findViewById(R.id.iv_group_detail_back);
        mCancel = findViewById(R.id.tv_group_detail_cancel);
        gv_member_list = findViewById(R.id.gv_member_list);
        btn_exit_or_release_group = findViewById(R.id.btn_exit_or_release_group);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 2){
            // 获取返回的准备邀请的群成员信息
            String[] resultMembers = data.getStringArrayExtra("members");

            if (resultMembers == null){
                resultMembers = new String[0];
            }

            String[] members = resultMembers;
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {


                        EMClient.getInstance().groupManager().addUsersToGroup(emGroup.getGroupId(), members);

                        Log.e(TAG, "run: 发送群邀请成功 membes = "+ members );
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this, "发送群邀请成功", Toast.LENGTH_SHORT).show();
                                getMembersFromHxServer();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        Log.e(TAG, "run: 发送群邀请失败 membes = "+ members + " 原因： " + e.getMessage() );

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this, "发送群邀请失败", Toast.LENGTH_SHORT).show();

                                getMembersFromHxServer();
                            }
                        });
                    }
                }
            });
        }
    }

    private void showReleaseGroupDialog(String groupName){
        CustomDialog customDialog = new CustomDialog(GroupDetailActivity.this);
        customDialog.setTittle("解散群")
                .setMsg("您需要解散群 "+ groupName + " 吗?")
                .setNegative("取消")
                .setPositive("确定")
                .setOnClickButtonListener(new CustomDialog.OnClickButtonListener() {
                    @Override
                    public void OnClickNegative() {
                        customDialog.dismiss();
                    }

                    @Override
                    public void OnClickPositive() {
                        releaseGroup();
                        customDialog.dismiss();
                    }
                }).show();
    }

    private void showDeleteMemberDialog(UserInfo user){
        CustomDialog customDialog = new CustomDialog(GroupDetailActivity.this);
        customDialog.setTittle("删除群成员")
                .setMsg("您需要删除群成员 "+ user.getName() + " 吗?")
                .setNegative("取消")
                .setPositive("确定")
                .setOnClickButtonListener(new CustomDialog.OnClickButtonListener() {
                    @Override
                    public void OnClickNegative() {
                        customDialog.dismiss();
                    }

                    @Override
                    public void OnClickPositive() {
                        deleteMember(user);
                        customDialog.dismiss();
                    }
                }).show();
    }

    private void deleteMember(UserInfo user){
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 从环信服务器中删除群成员
                    EMClient.getInstance().groupManager().removeUserFromGroup(emGroup.getGroupId(), user.getHxid());

                    // 更新页面
                    getMembersFromHxServer();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this, "删除成员 "+ user.getName() + "成功", Toast.LENGTH_SHORT).show();
                        }
                    });

                } catch (HyphenateException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this, "删除成员 "+ user.getName() + "失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void releaseGroup() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {

            @Override
            public void run() {
                try {
                    //去环信服务器解散群
                    EMClient.getInstance().groupManager().destroyGroup(emGroup.getGroupId());

                    // 发送解散群/退群的广播
                    exitGroupBroadCast();

                    // 更新页面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this, "解散群成功", Toast.LENGTH_SHORT).show();

                            // 结束当前页面
                            finish();
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    // 更新页面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this, "解散群失败，原因："+e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void showSignOutGroupDialog(String groupName) {
        CustomDialog customDialog = new CustomDialog(GroupDetailActivity.this);
        customDialog.setTittle("退 群")
                .setMsg("您需要退出群 "+ groupName + " 吗?")
                .setNegative("取消")
                .setPositive("确定")
                .setOnClickButtonListener(new CustomDialog.OnClickButtonListener() {
                    @Override
                    public void OnClickNegative() {
                        customDialog.dismiss();
                    }

                    @Override
                    public void OnClickPositive() {
                        signOutGroup();
                        customDialog.dismiss();
                    }
                }).show();
    }

    private void signOutGroup() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //告知环信服务器退群
                    EMClient.getInstance().groupManager().leaveGroup(emGroup.getGroupId());

                    // 发送退群的广播
                    exitGroupBroadCast();

                    // 更新页面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this, "退群成功", Toast.LENGTH_SHORT).show();

                            // 结束当前页面
                            finish();
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    // 更新页面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this, "退群失败，原因："+e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (emGroup.getGroupPermissionType().equals("owner")){
            tv_group_detail_counts.setText("群成员: "+ emGroup.getMemberCount());
        }else {
            tv_group_detail_counts.setText("群成员: "+ (emGroup.getMemberCount() - 1));
        }
    }

}